package cn.learn.util;

import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 请求返回的统一格式
 *
 * @author huangyezhan
 * @date 2018年06月02日16:55
 */
@Getter
public class RestResponse<T> {
    private static final Logger logger = LoggerFactory.getLogger(RestResponse.class);
    private boolean success;
    private String  errorCode;
    private String  errorMsg;
    private T       data;

    public RestResponse() {
    }


    public void setData(T data) {
        this.data = data;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }


    public static RestResponse success() {
        return success((Object) null);
    }

    public static RestResponse success(Object data) {
        RestResponse restResponse = new RestResponse();
        restResponse.setSuccess(true);
        restResponse.setData(data);
        if (logger.isDebugEnabled()) {
            logger.debug("输出响应：" + restResponse);
        }
        return restResponse;
    }

    public static RestResponse failed(String errorCode, String errorMsg) {
        RestResponse restResponse = new RestResponse();
        restResponse.setSuccess(false);
        restResponse.setErrorCode(errorCode);
        restResponse.setErrorMsg(errorMsg);
        return restResponse;
    }

    public <T> RestResponse<T> wrapIndicateTypeRestResponse(T data) {
        RestResponse<T> restResponse = new RestResponse();
        restResponse.setSuccess(this.isSuccess());
        restResponse.setErrorMsg(this.getErrorMsg());
        restResponse.setErrorCode(this.getErrorCode());
        restResponse.setData(data);
        return restResponse;
    }

    public static RestResponse failed(ApiReturnCodeEnum error) {
        RestResponse restResponse = new RestResponse();
        restResponse.setSuccess(false);
        restResponse.setErrorCode(error.getCode());
        restResponse.setErrorMsg(error.getMsg());
        return restResponse;
    }


}
